package com.hzit.proxy.base;

import com.alibaba.fastjson.JSONObject;
import com.hzit.net.RedisUtils;
import com.hzit.net.WXNetUtil;

/**
 * 获取access_token内容
 */
public class AccessToken {

    private static final String appid = "wx405f68216288b619";
    private static final String appsecret = "8d88a36a031b1f6b83b9cb29399221e7";

    /**
     * 获取token
     *
     * @return
     */
    public static String getToken() {
        String key = "weixin:token";
        //1.从redis中获取token
        String token = RedisUtils.get(key);

        //2.如果存放直接返回token
        if (token != null) {
            return token;
        }
        //3.如果不存在 远程调用weixin服务器中的token,并且存入redis中 有效期不能超过2小时
        String remoteToken = remote();
        if(remoteToken!=null){
            RedisUtils.set(key,remoteToken,7000); //不能大于7200
            return remoteToken;
        }
        return null;
    }

    private static String remote() {
        System.out.println("----->远程访问token>--------");
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;

        //{"access_token":"ACCESS_TOKEN","expires_in":7200}
        String result = WXNetUtil.get(url);

        //解析结果集，获取token
        //json字符串转为json对象   java对象
        JSONObject jsonObject = JSONObject.parseObject(result);

        if (jsonObject.containsKey("access_token")) {
            String token = jsonObject.getString("access_token");
            return token;
        }
        System.err.println("erro:" + result);
        return null;
    }

    public static void main(String[] args) {
        String token = getToken();
        System.out.println(token);
    }

}
